package task.www.lagou.app;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;
import task.www.lagou.utils.DruidUtils;

import java.sql.Date;
import java.sql.SQLException;

/**
 * 实现卡号：1122334455向55443332211转账5000元的操作；
 */
public class TestQuestion1 {
    @Test
    public void testTransaction(){
        transaction("1122334455","55443332211",5000);
    }
    public boolean transaction(String fromCardId ,String toCardId ,double balance){
        QueryRunner qr =new QueryRunner(DruidUtils.getDataSource());
        String sql1 = "select balance from account where card = ?";
        try {
            //查询付款人的剩余金额
            Double fromId = (Double)qr.query(sql1,new ScalarHandler<>(),fromCardId);
            Double  toId= (Double)qr.query(sql1,new ScalarHandler<>(),toCardId);

            System.out.println(fromId);
            System.out.println(toId);
            //如果付款人剩余金额足额
            if(fromId >= balance){
                //统计交易金额
                fromId -= balance;
                toId += balance;
                String sql2 = "update account set balance = ? where card = ?";

                //更新交易金额

                qr.update(sql2,new Object[]{fromId,fromCardId});
                qr.update(sql2,new Object[]{toId,toCardId});

                String sql3 = "insert into transaction values(null, ?, ?, ?, ?)";
                long success = System.currentTimeMillis();

                System.out.println(success);
                //更新transaction表
                qr.update(sql3,new Object[]{fromCardId,"转出",balance,new Date(success)});
                qr.update(sql3,new Object[]{toCardId,"转入",balance,new Date(success)});

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
